<!-- Leon.Ji -->
<template>
  <div v-if="moreMenuObj.hasMenu" class="more_div">
    <el-popover placement="top"  offset=0
                v-if="comAppendToBody"
                width="200"
                popper-class="token-popover"
                v-model="visible">
      <div class="token-list"
           v-if="moreMenuObj.hasMenu&&showMenuList&&showMenuList.length>0"
           :style="{padding:isShowBotList?'8px 0px':''}">
        <div v-if="isShowBotList"
             class="cursor-pointer"
             style="color:#000;font-size:14px;font-weight: 600;border-bottom:solid 1px #F0F0F0;height: 34px;line-height: 30px;"
             @click="gotoback">
          <i class="el-icon-arrow-left"
             style="margin-left:16px;"></i>&nbsp;&nbsp;Linked Bots
        </div>
        <div class="token-list-item">
          <div v-if="!isShowBotList">
            <div style="max-height: 10%;overflow:auto;padding: 0 0 8px;">
              <div class="group-item group-item--create flex  items-center"
                   v-if="moreMenuObj.hasBot&&!IsPresentShow">

                <span class="cuifont icon_logo_bots"
                      style="font-size:14px;"></span>
                <span @click.stop="clickGenerateBot()"
                      style="margin-left:10px;">{{'Create Bot'}}</span>

                <span v-if="Array.isArray(botList)&&botList.length>0"
                      @click="showBotList"
                      class="group-item-tag flex items-center justify-center">
                  {{botList.length}}</span>
              </div>
              <div class="group-item flex items-center"
                   v-for="(its, ii) in showMenuList"
                   :key="ii"
                   @click="clickMoreMenuItem(its)" >
                   <div v-if="its.label!=='Clone to'">
                    <i :class="its.icon"></i>
                    <span style="margin-left:10px;">{{its.label}}</span>
                   </div>

                <template v-if="its.label==='Clone to'">
                  <el-popover
                   placement="right"
                   width="210"
                   trigger="hover"
                    popper-class="mare-menu-dropdown-cloneto"
                  >
                  <div class="clone_to" @click="CloneToMyWidgets">Clone to "My widgets"</div>
                  <div class="clone_to" @click=cloneExistingDashboards>Clone to existing dashboards</div>
                  <div class="clone_to" @click=cloneNewDashboard>Clone to new dashboard</div>
                   <div  slot="reference">
                    <!-- <div>
                       <div class="el-icon-arrow-right" style="position: absolute;right: 5px;bottom: 7px;font-size: 14px;;"></div>
                     </div>  -->
                    <div>
                    <i :class="its.icon"></i>
                    <span style="margin-left:10px;">{{its.label}}</span>
                    <div class="el-icon-arrow-right" style="margin-left:70px;"></div>
                   </div>
                   </div>
                 </el-popover>
                </template>
              </div>
            </div>
          </div>
          <div v-if="isShowBotList">
            <div style="max-height: 10%;overflow:auto">
              <div class="group-item"
                   v-for="(its, ii) in botList"
                   :key="ii">
                <div style="display: flex;justify-content: space-between;align-items: center;">
                  <div style="display: block;max-width: 180px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                    <span>{{ its.name }}</span>
                  </div>
                  <div>
                    <i v-if="$hasPermission('sys:bots:edit')"
                       class="cuifont icon_edit"
                       style="cursor:pointer;font-size:14px;margin-right: 8px;"
                       @click="editBots(its.id)"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-button size="mini"
                 type=""
                 plain
                 slot="reference"
                 class="more-menu-btn"
                 style="width:24px;height:24px;border:none;background-color: transparent;;padding:0">
        <span class="el-icon-more"
              style="fontSize:14px;width:24px;height:24px;line-height:24px;backgroundColor:#F2F4F8;border-radius:50%"></span>
      </el-button>
    </el-popover>
    <el-button size="mini"
               v-else
               type=""
               @click="clickMoreMenuItem({type:'fullscreen'})"
               plain
               class="more-menu-btn"
               style="width:24px;height:24px;border:none;background-color: transparent;;padding:0">
        <span class="cuifont icon_fullscreen"
              style="fontSize:18px;width:24px;height:24px;line-height:24px;backgroundColor:#F2F4F8;border-radius:50%"></span>
    </el-button>
    <filterGadget ref="filter-gadget"
                  :slicer='slicer'
                  @updateQuery="updateQuery" />
    <AddUpdateBak ref="addUpdateBak"
                  :reselectVisible="reselectVisible"
                  :parentStateObj="botTem"
                  :botType="botType"
                  @closeQuery="closeQuery"></AddUpdateBak>
    <BdialogSelectDashboard ref="BdialogSelectDashboard"
                            :visible.sync="BdialogSelectDashboardVisible"
                            :widgetInfoLoading='widgetInfoLoading'
                            :widgetInfo='widgetInfo'
                            v-if="BdialogSelectDashboardVisible"
                            ></BdialogSelectDashboard> 
    <el-dialog :visible.sync="reportModalVisible"
               append-to-body
               :close-on-click-modal="false"
               custom-class="report-dialog"
               :title="'Add New Dashboard'"
               destroy-on-close
               width="450px">
      <AddReportForm v-if="reportModalVisible"
                     :resourceType="0"
                     :type="dashboardType"
                     :widgetInfo='widgetInfo'
                     @event:success="onAddSuccess" />
    </el-dialog>

    <SelectDashboardType :visible.sync="selectDashboardDialog"
                         @item-click="handleItemTypeClick" />  
    <CloneWidget :visible.sync="cloneWidgetModalVisible"
                 :gadgetId="gadgetId"
                 :resourceType="1"
                 v-if="cloneWidgetModalVisible"
                 @event:success="refreshWightList" />
                                           
                            

  </div>

</template>

<script>
import filterGadget from '@/components/dashboard-filter/index'
import { v4 } from 'uuid'
import { dashboardGadgetList } from '@/utils/data-json'
import AddUpdateBak from '@/views/modules/mspbots/bots-bak/my-bots/add-or-update-bak'
import { fetchWidgetInfo } from '@/api/new'
import BdialogSelectDashboard from '@/components/storybook/b-dialog-select-dashboard'
import bus from '@/components/storybook/utilties/bus'
import AddReportForm from '@/views/modules/report/components/add-report-form'
import SelectDashboardType from '@/views/modules/report/components/SelectDashboardType.vue'
import { getGadget } from '@/components/storybook/hooks/useGadget'
import CloneWidget from '@/views/modules/widget/components/clone-widget.vue'



export default {
  inject: {isQueryModel:{default:false}},
  components: { filterGadget, AddUpdateBak,BdialogSelectDashboard,AddReportForm,SelectDashboardType,CloneWidget},
  props: {
    gadgetId: {
      type: String,
      default: ''
    },
    gadgetType: {
      type: String,
      default: ''
    },
    slicer: {
      type: Object,
      default: () => { }
    },
     fitToHeight: {
      type: Boolean,
      default: false
    },
    widgetName: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    businessType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      botList: [],
      botTem: -1,
      botType: '',
      loading: false,
      reselectVisible: true,
      visible: false,
      isShowBotList: false,
      reportModalVisible: false,
      selectDashboardDialog: false,
      dashboardType: '',
      cloneWidgetModalVisible: false,
      BdialogSelectDashboardVisible: false,
      widgetInfoLoading :true,
      widgetInfo: {}
    }
  },
  watch: {
    visible: {
      handler: function (val) {
        if (val) {
          this.initBotList()
        } else {
          this.isShowBotList = false
        }
      },
      immediate: true
    }
  },
  computed: {
    comAppendToBody () {
      return !this.isFullScreen()?!this.fitToHeight:false
    },
    moreMenuObj () {
      try {
        return dashboardGadgetList.find(e => e.key === this.gadgetType).moreMenu
      } catch (error) {
        return { hasMenu: false, menuList: [] }
      }
    },
    showMenuList () {
      let temp = []
      // let tempList = []
      if (this.hasdesignRulePermission()) {
        temp = this.moreMenuObj.menuList
      } else {
        temp = this.moreMenuObj.menuList.filter(item => {
          return item.type !== 'edit'
        })
      }
      let path = window.location.pathname
      if (path.includes('present')) {
        temp = this.moreMenuObj.menuList.filter(item => {
          return item.type !== 'edit' && item.type !== 'copyurl' && item.type !== 'fullscreen'
        })
      }
      if (path.includes('portal')) {
        temp = this.moreMenuObj.menuList.filter(item => {
          return item.type !== 'edit' && item.type !== 'copyurl' && item.type !== 'fullscreen'
        })
      }
      if(this.gadgetType === 'sunburstgadget'){
        temp = this.moreMenuObj.menuList.filter(item => {
          return item.type !== 'filter'
        })
      }

      temp = this._.uniqBy(temp, 'type')
      if (this.isQueryModel && this.isQueryModel()) {
        temp = temp.filter(i => i.type !== 'edit' && i.type !== 'copyurl' && i.type !== 'fullscreen')
      }
      if ((this.businessType && this.businessType === 'MSPbots Internal') || !this.$hasPermission(`sys:widget:clone`)) {
        temp = temp.filter(i => i.type !== 'cloneto' )
      }
      return temp
    },
    IsPresentShow () {
      let temp = false
      let path = window.location.pathname
      if (path.includes('present') || path.includes('publicReport') || path.includes('publicReportPdf') || path.includes('/portal')) {
        temp = true
      }
      return temp
    }
  },
  methods: {
    menuComponentFilter () {
      this.$refs['filter-gadget'].init(this.gadgetId)
    },
    gotoback () {
      this.isShowBotList = false
    },
    hasdesignRulePermission () {
      let widgetadmin = this.$hasPermission('sys:widget:widgetadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:widget:edit') ? 1 : 0
      let isCustom = this.businessType === 'Custom' ? 1 : 0
      if (widgetadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    clickMoreMenuItem (data) {
      switch (data.type) {
        case 'filter':
          this.menuComponentFilter()
          break
        case 'refresh':
          this.updateQuery()
          break
        case 'copyurl':
          this.shareWidget()
          break
        case 'edit':
          this.showQueryModel()
          break
        case 'fullscreen':
          this.fullScreen()
          break

        default:
          break
      }
    },
    shareWidget () {
      let url = ''
      var loca = window.location
      var path = '/Widgets'
      if (this.businessType === 'MSPbots Internal') {
        path = '/CrossTenantWidget'
      }
      var baseUrl = loca.origin + path
      url = baseUrl + '?widgetId=' + this.id
      const oInput = document.createElement('input')
      document.body.appendChild(oInput)
      oInput.value = url
      oInput.select()
      document.execCommand('Copy')
      oInput.remove()
      this.$message.success('Copy Success!')
    },
    updateQuery () {
      this.$emit('updateQuery')
    },
    showQueryModel () {
      this.$emit('showQueryModel')
    },
    isFullScreen() {
      return  !!document.getElementsByClassName('fullScreenDialog')[0]
    },
    fullScreen () {
      this.$emit('fullScreen')
      this.visible=false
    },
    visibleChange (e) {
      if (e) {
        this.initBotList()
      }
    },
    showBotList () {
      this.isShowBotList = !this.isShowBotList
    },
    editBots (id) {
      window.open(`${window.location.origin}/bot-${id}?botId=${id}&pageid=botdetail&design=design`, '_blank')
    },
    initBotList () {
      this.loading = true
      const params = {
        datasourceId: this.gadgetId
      }
      this.$interface.bots.getWidgetByBotsList(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            let temp = []
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i]
              // if (i === 0) {
              //   element.divided = 'divided'
              // }
              temp.push({
                id: element.id,
                name: element.name,
                divided: element.divided
              })
            }
            this.botList = res.data
            this.$forceUpdate()
          }
          this.$forceUpdate()
          this.loading = false
          if (!(this.botList.length > 0)) {
            this.clickGenerateBotItem('generateBot')
          }
        })
        .catch(() => { })
    },
    clickGenerateBot () {
      // this.$store.commit('DEFAULTWIDGET', this.gadgetId)
      this.addOrUpdateNewBots(this.gadgetId)
    },
    addOrUpdateNewBots (gadgetId) {
      this.$store.commit('BOTFORMEDIT', false)
      this.$store.commit('BOTFORMWIDGET', true)
      this.$store.commit('DEFAULTTAB', true)
      this.$nextTick(() => {
        this.$refs.addUpdateBak.init(gadgetId)
        this.$refs.addUpdateBak.dataForm.name = `Monitoring [${this.widgetName}] for`
        this.$refs.addUpdateBak.dataForm.description = `This bot is generated for monitoring [${this.widgetName}] for`
      })
      let item = {
        item: {
          id: '1351882044666384386',
          tenantCode: '1001',
          name: 'Quality Assurance Bot',
          icon: this.$ossLink + '/app/bot/bot-icon-normal.png',
          description: 'QA bot compare the data with predefined rules, send the alert to user via Microsoft Teams chat or Channel, if issue persists, alert the management to take actions.',
          enable: null,
          url: null,
          version: null,
          createTime: null,
          updateTime: null,
          triggerType: 'Timed',
          integration: null,
          integrationCode: null,
          integrationIcon: null,
          level: null,
          creator: null,
          updateBy: null,
          applyTenant: null,
          originalId: null,
          escalation: null,
          alert: null,
          params: null,
          flowSetting: null,
          shared: null,
          sysBotScriptList: null,
          businessType: null,
          status: null,
          publishTime: null,
          internal: null,
          teamId: null,
          teamName: null,
          creatorName: null,
          updateByName: null,
          classification: 'Quality Assurance Bot',
          da: null,
          po: null,
          jiraNumber: null,
          updated: null
        },
        type: 'template'
      }
      this.botTem = item.item
      this.botType = item.type
    },
    closeQuery () {
      //
      this.$root.eventBus.$emit('close')
    },
    cloneExistingDashboards(){
      this.getWidgetInfo()  
      this.BdialogSelectDashboardVisible = true
    },
    cloneNewDashboard(){
      this.getWidgetInfo() 
      this.selectDashboardDialog = true
    },
    async getWidgetInfo (gadgetId) {
      try {
              const params = {
                gadgetId: this.gadgetId,
                includeSql: true
              }
              const { data: response } = await fetchWidgetInfo(params)
              if (response.code !== 0) {
                return {}
              }
              this.widgetInfo = response.data || {}
              this.widgetInfoLoading = false
         } catch (error) {
          console.log(error);
           this.widgetInfoLoading = false
         }
    },
    handleItemTypeClick (item) {
      this.dashboardType = item.key
    },
    onAddSuccess (data = {}) {
      this.selectDashboardDialog = false
      this.reportModalVisible = false
      if (this.dashboardType === 'report_layout') {
        this.$router.push({
          path: `dashboard-${data.id}`,
          query: {
            pageid: data.id,
            name: data.name,
            init: true
          }
        })
      } else {
        this.$router.push({
          path: `report-${data.id}`,
          query: {
            pageid: data.id,
            name: data.name,
            init: true
          }
        })
      }
      bus.$emit('cloneNewDashboardRefresh')
    },
    openReportModal() {
      this.reportModalVisible = true
    },
    CloneToMyWidgets(){
      this.cloneWidgetModalVisible = true
    },
    refreshWightList () {
      bus.$emit('event:refresh-widget-list')
    },

  }
}
</script>

<style scoped lang='scss'>
.token-list {
  &-item {
    .group-title {
      color: rgba(0, 0, 0, 0.5);
      font-size: 12px;
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin-top: 10px;
    }
    .group-item {
      height: 34px;
      line-height: 34px;
      //padding: 0 10px 0 19px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
      &:hover {
        background: #f5f7fa;
      }
    }
  }
}
 .clone_to {
      height: 34px;
      font-size: 14px;
      line-height: 34px;
      cursor: pointer;
      padding: 0 12px;
    } 
  .clone_to:hover {
      background-color: #f5f7fa;
    }
</style>

<style lang='scss'>
.token-popover {
  padding: 0;
  .token-list {
    &-item {
      .group-item {
        height: 34px;
        font-size: 14px;
        padding: 0 16px;
        &--create {
          height: 46px;
          color: #0050b3;
          box-shadow: inset 0px -1px 0px 0px #f0f0f0;
        }
        &-tag {
          margin-left: auto;
          background-color: #f0f0f0;
          border-radius: 10px;
          height: 20px;
          color: #0050b3;
          padding: 0px 8px;
        }
      }
      .group-title {
      }
    }
  }
}
.more_menu_box {
  width:24px;height:100%;position:absolute;top:0;right:0;z-index:2019;background:#ffffff;display:flex;justify-content:center;align-items:center;margin-right:16px;
  // display: none;
}
.more_menu_box:hover {
  display: block;

}
.more-menu-btn .el-icon-more {
  display: none;
}
.more-menu-btn:hover .el-icon-more {
  display: block;
  background-color: #DDE1E6!important;
}
.more_div {
  position: absolute;
  top: 4px;
  right: 9px;
}
.mare-menu-dropdown-cloneto {
     padding:0 !important;
  }

</style>
